package com.example.mulittenantdemo.util;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.example.mulittenantdemo.domain.Tenant;
import com.example.mulittenantdemo.service.TenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.List;

@Component
public class MyDomic{
    @Autowired
    private DataSource dataSource;
    @Autowired
    private DefaultDataSourceCreator dataSourceCreator;

    @Autowired
    TenantService tenantService;
    @Autowired
    public void init(){

        List<Tenant> list = tenantService.list();
        for (Tenant tenant : list) {
            DataSourceProperty dataSourceProperty = new DataSourceProperty();
            dataSourceProperty.setUrl("jdbc:mysql://127.0.0.1:3306/"+tenant.getDb()+"?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF8&useSSL=false");
            dataSourceProperty.setUsername(tenant.getUser());
            dataSourceProperty.setPassword(tenant.getPwd());
            dataSourceProperty.setDriverClassName("com.mysql.cj.jdbc.Driver");

            DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
            DataSource dataSource = dataSourceCreator.createDataSource(dataSourceProperty);
            ds.addDataSource(tenant.getCode(), dataSource);
        }


    }
}
